<?php
namespace Admin\Controller;
use Common\Controller\RequestController;
use PHPWord;

/**
 * 信息录入查看管理
 */
class ApplyController extends AdminController
{
    public $educationItems     = [1 => '小学及以下', '初中', '高中', '大专', '本科', '硕士研究生及以上'];//学历

    public $houseTypeItems     = ['无', '商品房无贷款', '商品房有贷款', '自建房', '房改房', '租房', '拆迁安置房', '单位宿舍', '商铺有贷款', '商铺无贷款', '公租',];//房屋类型

    public $creditQ            = ['妈妈的名字', '小学的名字'];//信用卡问题

    public $companyNatureItems = ['自由职业', '个体户', '股份公司', '国家机关', '事业单位', '外资或合资公司', '民营企业','私营企业'];//单位性质

    public $maritalStatusItems = ['未婚', '离异', '丧偶', '已婚有子女', '已婚无子女'];//婚姻状态

    public $serviceSourceItems = ['4S店', '二级经销商', '二手车经销商', '租赁公司', '其他'];//业务来源

    public $relationship       = ['父亲', '母亲', '哥哥', '姐姐', '祖父', '祖母', '外祖父', '外祖母', '兄弟', '姐妹', '兄妹', '姐弟', '朋友', '儿子', '女儿','妻子'];//紧急联系人关系

    public $distributorItems   = ['无', '签约经销商'];//经销商类别

    public $carFirmItems       = ['简易贷', '标准贷', '租赁'];//业务类型

    public $carTypeItems       = ['国产车','进口车' ];//车辆类型

    public $carModelItems      = ['新车', '二手车', '存量车', '商用车',];//车辆性质

    public $onCardItems        = [ '私牌','公牌'];//上牌类型

    public $yearLimitItems     = [12, 24, 36, 48, 60];//年限

    public $workYearItems      = ['无', '3年以下', '3年-5年', '5年及以上'];//工作年限

    public $statusItems        = ['-1' => '全部', '征信待提交', '征信待审核', '申请待审核', '删除', '央行征信通过', '拒绝贷款', '申请待提交', 9 => '审核不通过', 10 => '审核已完成', 901 => '央行征信不通过', 902 => '公检法审核不通过'];

    public $smallRateItems     = ['1' => '有', '0' => '无'];//有无小利率

    public function showPic()
    {
        $pic_url = $_GET['pic_url'];

        $arrPics = explode(',', $pic_url);

        $this->assign('arrPics',$arrPics);
        $this->display();
    }

    public function readExcel()
    {
        if (IS_POST) {
            $nUserId = I('post.user_id', '', 'intval');
            $_tmpUser = $this->getInfo('*', 'user', 'id = ' . $nUserId);//用户信息

            if (is_null($_tmpUser)) {
                $this->error('该用户不存在，请核实或联系管理员');
            }
            $_bank = $this->getInfo('*', 'bank', 'id = ' . $_tmpUser['loan_bank_id']);//银行规则

            switch ($_bank['bank_name']) {
                case '浙江诸暨农村商业银行股份有限公司':
                    $file_name = 'zhuji.xls';
                    break;

                case '中国建设银行股份有限公司杭州延安支行':
                    $file_name = 'jianshe.xls';
                    break;

                case '杭州联合农村商业银行股份有限公司':
                    $file_name = 'lianhe.xls';
                    break;

                case '杭州银行股份有限公司清泰支行':
                    $file_name = 'hangzhou.xls';
                    break;

                case '浙江萧山农村商业银行股份有限公司杭州城中':
                    $file_name = 'xiaoshan.xls';
                    break;

                default:
                    break;
            }

            $_tmpCarInfo = $this->getInfo('*', 'car_info', 'user_id = ' . $nUserId);//车辆信息
            if (is_null($_tmpCarInfo)) {
                $this->error('请先完善车辆信息');
            }
            $_bankRule = $this->getInfo('*', 'bank_rule', 'bank_id = ' . $_tmpUser['loan_bank_id']);//银行规则
            if (is_null($_bankRule)) {
                $this->error('请联系管理员，维护银行规则');
            }
            $_car = $this->getInfo('*', 'car', 'type_id = ' . $_tmpCarInfo['car_form_id']);//车型
            if (is_null($_car)) {
                $this->error('该用户选择的车型不存在');
            }
            $_advanceInfo = $this->getInfo('*', 'advance_info', 'user_id = ' . $nUserId);//垫资信息
            if (is_null($_advanceInfo)) {
                $this->error('请先完善垫资信息');
            }

            set_time_limit(0);
            ignore_user_abort(true);//检测用户断开

            $savePath = './Uploads/excel/';


            include VENDOR_PATH . 'PHPExcel/PHPExcel.php';


            //读取 写入
            $objReader = \PHPExcel_IOFactory::createReaderForFile($savePath . $file_name);
            $objPHPExcel = $objReader->load($savePath . $file_name);

            $objPHPExcel->setActiveSheetIndex(0);
            // 借款人信息
            $objPHPExcel->getActiveSheet()->setCellValue('G1', $_tmpUser['user_name']);//姓名
            $objPHPExcel->getActiveSheet()->setCellValue('J15', $_tmpUser['identity_no']);//身份证
            $objPHPExcel->getActiveSheet()->setCellValue('V15', $_tmpUser['telephone']);//电话
            $objPHPExcel->getActiveSheet()->setCellValue('AF15', $_tmpUser['sex'] == 1 ? '男' : '女');//性别
            $objPHPExcel->getActiveSheet()->setCellValue('AP15', $_tmpUser['marital_status']);//婚姻状况
            $objPHPExcel->getActiveSheet()->setCellValue('BE15', $_tmpUser['address']);//home_area_id 户籍所在地
            $objPHPExcel->getActiveSheet()->setCellValue('G16', $this->educationItems[$_tmpUser['education']]);//文化程度
            $objPHPExcel->getActiveSheet()->setCellValue('V16', $_tmpUser['company_tel']);//单位电话
            $objPHPExcel->getActiveSheet()->setCellValue('AF16', $this->companyNatureItems[$_tmpUser['company_nature']]);//单位性质
            $objPHPExcel->getActiveSheet()->setCellValue('AY16', $_tmpUser['company_office']);//单位职位
            $objPHPExcel->getActiveSheet()->setCellValue('G17', $_tmpUser['work_company']);//工作单位
            $objPHPExcel->getActiveSheet()->setCellValue('AF17', $_tmpUser['work_life']);//工作年限
            $objPHPExcel->getActiveSheet()->setCellValue('AY17', $_tmpUser['month_income'] * 12 / 10000);//年收入
            $objPHPExcel->getActiveSheet()->setCellValue('G18', $_tmpUser['now_address']);//现居住地
            // 配偶信息
            $objPHPExcel->getActiveSheet()->setCellValue('G21', $_tmpUser['spouse_name']);//配偶姓名
            $objPHPExcel->getActiveSheet()->setCellValue('J21', $_tmpUser['spouse_identity_no']);
            $objPHPExcel->getActiveSheet()->setCellValue('AF21', '女');
            $objPHPExcel->getActiveSheet()->setCellValue('G22', $this->educationItems[$_tmpUser['spouse_education']]);
            $objPHPExcel->getActiveSheet()->setCellValue('BE21', $_tmpUser['spouse_address']);
            $objPHPExcel->getActiveSheet()->setCellValue('V21', $_tmpUser['spouse_telephone']);
            $objPHPExcel->getActiveSheet()->setCellValue('AY22', $_tmpUser['spouse_position']);
            $objPHPExcel->getActiveSheet()->setCellValue('AF22', $_tmpUser['spouse_company_nature']);
            $objPHPExcel->getActiveSheet()->setCellValue('G23', $_tmpUser['spouse_company']);
            // $objPHPExcel->getActiveSheet()->setCellValue('D9',$_tmpUser['spouse_company_address']);
            $objPHPExcel->getActiveSheet()->setCellValue('AF23', $_tmpUser['spouse_work_life']);
            $objPHPExcel->getActiveSheet()->setCellValue('AY23', $_tmpUser['spouse_month_income'] * 12 / 10000);
            // 车辆信息
            $objPHPExcel->getActiveSheet()->setCellValue('M2', $_tmpCarInfo['sale_price']);
            $objPHPExcel->getActiveSheet()->setCellValue('M4', $_tmpCarInfo['real_loan_quota']);
            $objPHPExcel->getActiveSheet()->setCellValue('G5', $_tmpCarInfo['term'] / 12);
            $objPHPExcel->getActiveSheet()->setCellValue('K5', $_tmpCarInfo['term']);
            $objPHPExcel->getActiveSheet()->setCellValue('AD5', $_tmpCarInfo['car_type']);
            $objPHPExcel->getActiveSheet()->setCellValue('M1', $_car['type_name']);
            $objPHPExcel->getActiveSheet()->setCellValue('V1', $_car['type_name']);
            $objPHPExcel->getActiveSheet()->setCellValue('M8', $_tmpCarInfo['company_rate'] - $_bankRule['rate'] * 100);
            $objPHPExcel->getActiveSheet()->setCellValue('M10', $_bankRule['rate'] * 100);//银行手续费
            $objPHPExcel->getActiveSheet()->setCellValue('F14', $_advanceInfo['performance_fee']);
            $objPHPExcel->getActiveSheet()->setCellValue('F16', $_tmpCarInfo['license_area']);
            $objPHPExcel->getActiveSheet()->setCellValue('F17', $_tmpCarInfo['license_type'] == 1 ? '公牌' : '私牌');
            $objPHPExcel->getActiveSheet()->setCellValue('F19', $_tmpCarInfo['month_repayment']);

            header("Pragma: public");
            header("Expires: 0");
            header("Cache-Control:must-revalidate, post-check=0, pre-check=0");
            header("Content-Type:application/force-download");
            header("Content-Type:application/vnd.ms-execl");
            header("Content-Type:application/octet-stream");
            header("Content-Type:application/download");;
            header('Content-Disposition:attachment;filename=' . $_tmpUser['user_name'] . $file_name);
            header("Content-Transfer-Encoding:binary");
            $objWriter = new \PHPExcel_Writer_Excel5($objPHPExcel);
            $objWriter->save($_tmpUser['user_name'] . $file_name);
            $objWriter->save('php://output');
            exit();

            // } else {
            // 	$this->error('附件不能为空！');
            // }

        } else {
            $nUserId = I('get.user_id', '', 'intval');
            $_user = $this->getInfo('*', 'user', 'id = ' . $nUserId);//用户信息
            $_bank = $this->getInfo('*', 'bank', 'id = ' . $_user['loan_bank_id']);//银行规则
            $this->assign('user', $_user);
            $this->assign('bank', $_bank);
            $this->display();
        }
    }

    public function read($filename, $encode = 'utf-8')
    {
        include VENDOR_PATH . 'PHPExcel/PHPExcel.php';
        $objReader = \PHPExcel_IOFactory::createReader('Excel5');
        $objReader->setReadDataOnly(true);
        $objPHPExcel = $objReader->load($filename);
        $objWorksheet = $objPHPExcel->getActiveSheet();
        $highestRow = $objWorksheet->getHighestRow();
        $highestColumn = $objWorksheet->getHighestColumn();
        $highestColumnIndex = \PHPExcel_Cell::columnIndexFromString($highestColumn);
        $temp = array();
        for ($row = 1; $row <= $highestRow; $row++) {//行数是以第1行开始
            for ($column = 0; $column < $highestColumnIndex; $column++) {//列数是以A列开始
                $temp[$row][] = $objWorksheet->getCellByColumnAndRow($column, $row)->getValue();
            }
        }
        return $temp;
    }

    protected function _initialize()
    {
        parent::_initialize();
    }

    public function preloanApply()
    {
        $pr_data["name"] = "皮晴晴";  // 姓名,必填
        $pr_data["id_number"] = "370404199006301915";  // 身份证号,必填
        $pr_data["mobile"] = "13333333333";  // 手机号,必填


        $ret = RequestController::pre_loan_apply($pr_data);
//	        $ret = RequestController::loadJsonByUrl('http://apitest.tongdun.cn/preloan/apply/v5?partner_code=ysdb&partner_key=37e8d2cd309c4cfbb28789dbecf95f67&app_name=ysdb_web','post');

        echo json_encode($ret);
    }

    public function preloanReport()
    {
        // $pr_data["report_id"] = "ER2017062911543516914183";  // 报告id
        $ret = RequestController::pre_loan_report('ER2017062914264815786946');
        echo json_encode($ret);
    }

    /**
     * [getAssureById 根据ID获取担保人详情]
     * @return [type] [ajax返回ID对应的担保人信息]
     * @author [NYJ]
     */
    public function getAssureById()
    {
        $nAssureId = $_POST['assure_id'];

        $strWhere = 'id = ' . $nAssureId;

        $assureInfo = $this->getInfo('*', 'assure', ['id' => $nAssureId]);

        echo json_encode($assureInfo);// $this->ajaxReturn($assureInfo,'根据ID获取担保人详情',1);

    }

    /**
     * [selectSeries 获取汽车系列]
     * @return [type] [ajax返回指定品牌下车系]
     * @author [NYJ]
     */
    public function selectSeries()
    {
        $nBrandId = $_POST['brand_id'];

        $strWhere = 'brand_id = ' . $nBrandId;

        $carSeries = $this->getList('*', 'series', $strWhere, 'id desc');

        echo json_encode($carSeries);// $this->ajaxReturn($carSeries,'获取汽车系列',1);

    }

    /**
     * [getCarSetInfo 根据车系id得到对应的车辆信息]
     * @return [type] [ajax返回车系下所有车型]
     * @author [NYJ]
     */
    public function getCarSetInfo()
    {
        $nCarSeriesId = $_POST['car_series_id'];

        $strWhere = 'car_series_id = ' . $nCarSeriesId;

        $carSetInfo = $this->getList('*', 'car', $strWhere, 'id desc');

        echo json_encode($carSetInfo);
    }

    public function check_result()
    {
        // $p_url_checkResult = 'http://116.228.224.58:8077/TMZLTEST/app/lywxapi.htm!?.url=qureyFinancePreApplyResultt';//测试提交
        $p_url_checkResult = 'http://happyleasing.cn/TMZL/app/lywxapi.htm!?.url=qureyFinancePreApplyResultt';//测试提交
        if (IS_POST) {
            $data = ['param' => json_encode([$_POST['applyId']])];

            $re = RequestController::loadStringByUrl($p_url_checkResult, 'post', $data);
            echo $re;
            exit();
        }
    }

    public function credit_check()
    {
        // $p_url = 'http://116.228.224.58:8077/TMZLTEST/app/lywxapi.htm!?.url=autoFinancingPreApplyt';//测试提交
        $p_url = 'http://happyleasing.cn/TMZL/app/lywxapi.htm!?.url=autoFinancingPreApplyt';

        if (IS_POST) {
            $data = ['param' => json_encode($_POST)];
            $re = RequestController::loadStringByUrl($p_url, 'post', $data);
            echo $re;
            exit();
        }

        $this->assign('nowTime', date('Y-m-d h:i:s'));
        $this->display();
    }

    /*信息详情*/
    public function detail_info()
    {
        $nUserId = $_GET["user_id"];
        $info = $this->getInfo('u.*,ad.name as admin_name', 'user as u', 'u.id=' . $nUserId, 'app_admins as ad on u.admin_id = ad.id');

        if (empty($info)) {
            $this->error('该ID为：' . $_GET['user_id'] . '获取信息失败');
        }

        $_tmpComTel = explode('-', $info['company_tel']);
        if (count($_tmpComTel) == 1) {
            $info['area_code'] = '';
        } else {
            $info['area_code'] = $_tmpComTel[0];
            $info['company_tel'] = $_tmpComTel[1];
        }

        // 担保人
        $assureList = $this->getList('id,user_name,identity_no', 'assure', ['user_id' => $nUserId], '');

        $assureInfo = $this->getList('*', 'assure', 'user_id = ' . $nUserId,'');

        // 紧急联系人
        $contactors = $this->getList('*', 'emergency_contact', 'user_id = ' . $nUserId, 'id desc');
        // 垫资信息
        $advanceInfo = $this->getList('*', 'advance_info', 'user_id = ' . $nUserId, 'id desc');
        // 车辆信息
        // $carInfo        = $this->getList('*','car_info','user_id = '.$nUserId,'id desc',);
        $carInfo = $this->getInfo('ci.*,c.initial,c.brand_name,c.brand_id,c.car_series_name,c.car_series_id,c.type_name,c.type_id,c.guide_price,c.seat_num',
            'car_info ci', 'ci.user_id = ' . $nUserId, 'left join app_car c on c.type_id = ci.car_form_id ');

        $needUploadFiles = [];
        if (!is_null($carInfo)) {
            $strWhere = 'business_type = ' . $carInfo['business_type'] . ' and models_form = ' . $carInfo['models_form'] . ' and license_type = ' . $carInfo['license_type'] . ' and bank_id = ' . $info['loan_bank_id'] . ' and (file_type=0';
            if ($assureList != null) {
                $strWhere .= ' or file_type=2';
            }
            if ($info['spouse_name'] != null) {
                $strWhere .= ' or file_type=1';
            }
            $strWhere .= ')';
            $needUploadFiles = $this->getList('*', 'file_set', $strWhere, '');

            $uploadFiles = $this->getList('*', 'user_file', 'user_id=' . $nUserId . ' and status=0', 'id desc');

            foreach($needUploadFiles as &$k1)
            {
                foreach($uploadFiles as $k2)
                {
                    if($k1['e_file_key']==$k2['e_file_key'])
                    {
                        $k1['file_dist']=$k2['file_dist'];
                    }
                }
            }
        }

        // 公司地址分解
        $c_areaInfo = $this->getAreaInfo($info['company_area_id']);
        // 户籍
        $h_areaInfo = $this->getAreaInfo($info['home_area_id']);
        // 现居住地
        $now_areaInfo = $this->getAreaInfo($info['now_area_id']);
        // 配偶公司地址分解
        $s_c_areaInfo = $this->getAreaInfo($info['spouse_company_area_id']);
        // 配偶户籍
        $s_h_areaInfo = $this->getAreaInfo($info['spouse_area_id']);
        // 配偶现居住地
        $s_now_areaInfo = $this->getAreaInfo($info['spouse_now_area_id']);
        // 担保人公司地址分解
        $a_c_areaInfo = $this->getAreaInfo($assureInfo['company_areaid']);
        // 担保人户籍
        $a_h_areaInfo = $this->getAreaInfo($assureInfo['home_areaid']);
        // 担保人现居住地
        $a_now_areaInfo = $this->getAreaInfo($assureInfo['now_areaid']);
        // 汽车品牌
        $carBrand = $this->getList('*', 'brand', '', 'initial asc');
        // 银行规则
        $bank_rule = $this->getInfo('*', 'bank_rule', 'bank_id = ' . $info['loan_bank_id']);
        // 上牌地
        $licenseList = $this->getList('*', 'license', 'status = 0 and bank_id = ' . $info['loan_bank_id'] . ' and group_id = ' . $info['gpid'], 'id');

        //业务进度
        $check_info = $this->getList('*', 'check_log', 'user_id = ' . $nUserId, 'id');

//        print_r($needUploadFiles);die;
        $this->assign('checkInfo', $check_info);
        $this->assign('info', $info);
        $this->assign('educationItems', $this->educationItems);
        $this->assign('houseTypeItems', $this->houseTypeItems);
        $this->assign('creditQ', $this->creditQ);
        $this->assign('companyNatureItems', $this->companyNatureItems);
        $this->assign('maritalStatusItems', $this->maritalStatusItems);
        $this->assign('serviceSourceItems', $this->serviceSourceItems);
        $this->assign('relationship', $this->relationship);
        $this->assign('distributorItems', $this->distributorItems);
        $this->assign('contactors', $contactors);
        $this->assign('advanceInfo', $advanceInfo[0]);
        $this->assign('carInfo', $carInfo);
        // $areaList = $this->getAreaList();
        // 车辆信息参数
        $this->assign('smallRateItems', $this->smallRateItems);
        $this->assign('carFirmItems', $this->carFirmItems);
        $this->assign('carTypeItems', $this->carTypeItems);
        $this->assign('carModelItems', $this->carModelItems);
        $this->assign('onCardItems', $this->onCardItems);
        $this->assign('yearLimitItems', $this->yearLimitItems);
        $this->assign('workYearItems', $this->workYearItems);
        $this->assign('c_areaInfo', $c_areaInfo);
        $this->assign('h_areaInfo', $h_areaInfo);
        $this->assign('now_areaInfo', $now_areaInfo);
        $this->assign('carBrand', $carBrand);
        $this->assign('bank_rule', $bank_rule);
        $this->assign('licenseList', $licenseList);
        $this->assign('s_h_areaInfo', $s_h_areaInfo);
        $this->assign('s_c_areaInfo', $s_c_areaInfo);
        $this->assign('s_now_areaInfo', $s_now_areaInfo);
        $this->assign('assureInfo', $assureInfo);
        $this->assign('a_h_areaInfo', $a_h_areaInfo);
        $this->assign('a_c_areaInfo', $a_c_areaInfo);
        $this->assign('a_now_areaInfo', $a_now_areaInfo);
        $this->assign('needUploadFiles', $needUploadFiles);
        $this->assign('assureList', $assureList);
        $this->display();
    }

    /*获取新的银行利率*/
    public function getRate()
    {
        $term = $_POST['term'];
        $bank_id = $_POST['bank_id'];
        $models_form = $_POST['models_form'];
        $province = $_POST['province'];

        $Where = 'car_model = ' . $models_form . ' and bank_id=' . $bank_id . ' and year_limit=' . $term . ' and is_province=' . $province;
        $bank_rule = $this->getInfo('rate', 'bank_rule', $Where);
//		$carSetInfo   = $this->getList('*','car',$strWhere,'id desc');
        echo json_encode($bank_rule);
    }

    /*信息详情*/
    public function get_info($user_id)
    {
        $nUserId = $user_id;
        $info = $this->getInfo('u.*,ad.name as admin_name', 'user as u', 'u.id=' . $nUserId, 'app_admins as ad on u.admin_id = ad.id');

        if (empty($info)) {
            $this->error('该ID为：' . $_GET['user_id'] . '获取信息失败');
        }

        $_tmpComTel = explode('-', $info['company_tel']);
        if (count($_tmpComTel) == 1) {
            $info['area_code'] = '';
        } else {
            $info['area_code'] = $_tmpComTel[0];
            $info['company_tel'] = $_tmpComTel[1];
        }

        $assureInfo = $this->getList('*', 'assure', 'user_id = ' . $nUserId,'');

        // 紧急联系人
        $contactors = $this->getList('*', 'emergency_contact', 'user_id = ' . $nUserId, 'id desc');
        // 垫资信息
        $advanceInfo = $this->getList('*', 'advance_info', 'user_id = ' . $nUserId, 'id desc');
        // 车辆信息
        // $carInfo        = $this->getList('*','car_info','user_id = '.$nUserId,'id desc',);
        $carInfo = $this->getInfo('ci.*,c.initial,c.brand_name,c.brand_id,c.car_series_name,c.car_series_id,c.type_name,c.type_id,c.guide_price,c.seat_num',
            'car_info ci', 'ci.user_id = ' . $nUserId, 'left join app_car c on c.type_id = ci.car_form_id ');

//        $needUploadFiles = [];
//        if (!is_null($carInfo)) {
//            $strWhere = 'business_type = ' . $carInfo['business_type'] . ' and bank_id = ' . $info['loan_bank_id'];
//
//            $needUploadFiles = $this->getList('*', 'file_set', $strWhere, 'id desc');
//        }
        $needUploadFiles = $this->getList('*','user_file','user_id = '.$nUserId.' and status=0','id desc');

        $bank_Info       = $this->getInfo('*', 'bank', 'id=' . $info['loan_bank_id']);

        // 公司地址分解
        $c_areaInfo      = $this->getAreaInfo($info['company_area_id']);
        // 户籍
        $h_areaInfo      = $this->getAreaInfo($info['home_area_id']);
        // 现居住地
        $now_areaInfo    = $this->getAreaInfo($info['now_area_id']);
        // 配偶公司地址分解
        $s_c_areaInfo    = $this->getAreaInfo($info['spouse_company_area_id']);
        // 配偶户籍
        $s_h_areaInfo    = $this->getAreaInfo($info['spouse_area_id']);
        // 配偶现居住地
        $s_now_areaInfo  = $this->getAreaInfo($info['spouse_now_area_id']);
        // 担保人公司地址分解
        $a_c_areaInfo    = $this->getAreaInfo($assureInfo['company_areaid']);
        // 担保人户籍
        $a_h_areaInfo    = $this->getAreaInfo($assureInfo['home_areaid']);
        // 担保人现居住地
        $a_now_areaInfo  = $this->getAreaInfo($assureInfo['now_areaid']);
        // 汽车品牌
        $carBrand        = $this->getList('*', 'brand', '', 'initial asc');
        // 银行规则
        $bank_rule       = $this->getInfo('*', 'bank_rule', 'bank_id = ' . $info['loan_bank_id']);
        // 上牌地
        $licenseList     = $this->getList('*', 'license', 'bank_id = ' . $info['loan_bank_id'] . ' and group_id = ' . $info['gpid'], 'id');

        //业务进度
        $check_info      = $this->getList('*', 'check_log', 'user_id = ' . $nUserId, 'id desc');

        $this->assign('checkInfo', $check_info);
        $this->assign('info', $info);
        $this->assign('educationItems', $this->educationItems);
        $this->assign('houseTypeItems', $this->houseTypeItems);
        $this->assign('creditQ', $this->creditQ);
        $this->assign('companyNatureItems', $this->companyNatureItems);
        $this->assign('maritalStatusItems', $this->maritalStatusItems);
        $this->assign('serviceSourceItems', $this->serviceSourceItems);
        $this->assign('relationship', $this->relationship);
        $this->assign('distributorItems', $this->distributorItems);
        $this->assign('contactors', $contactors);
        $this->assign('advanceInfo', $advanceInfo[0]);
        $this->assign('carInfo', $carInfo);
        // $areaList = $this->getAreaList();
        // 车辆信息参数
        $this->assign('carFirmItems', $this->carFirmItems);
        $this->assign('carTypeItems', $this->carTypeItems);
        $this->assign('carModelItems', $this->carModelItems);
        $this->assign('onCardItems', $this->onCardItems);
        $this->assign('yearLimitItems', $this->yearLimitItems);
        $this->assign('workYearItems', $this->workYearItems);
        $this->assign('c_areaInfo', $c_areaInfo);
        $this->assign('h_areaInfo', $h_areaInfo);
        $this->assign('now_areaInfo', $now_areaInfo);
        $this->assign('carBrand', $carBrand);
        $this->assign('bank_rule', $bank_rule);
        $this->assign('bankInfo', $bank_Info);
        $this->assign('licenseList', $licenseList);
        $this->assign('s_h_areaInfo', $s_h_areaInfo);
        $this->assign('s_c_areaInfo', $s_c_areaInfo);
        $this->assign('s_now_areaInfo', $s_now_areaInfo);
        $this->assign('assureInfo', $assureInfo);
        $this->assign('a_h_areaInfo', $a_h_areaInfo);
        $this->assign('a_c_areaInfo', $a_c_areaInfo);
        $this->assign('a_now_areaInfo', $a_now_areaInfo);
        $this->assign('needUploadFiles', $needUploadFiles);
    }

    /**
     * [根据areaId获取对应省市县]
     * @param  [type] $p_areaId [地区ID]
     * @return [type]           [含有省市县的数组]
     * @author [ NYJ]
     */
    protected function getAreaInfo($p_areaId = 110000)
    {
        if (is_null($p_areaId) || !is_numeric($p_areaId)) {
            $p_areaId = 110000;
        }

        $district = $p_areaId;
        $city     = floor($district / 100) * 100;
        $province = floor($district / 10000) * 10000;

        $area_where = 'area_id = ' . $district . ' or area_id = ' . $city . ' or area_id = ' . $province;
        $_tmp       = $this->getList('area_id,area_name', 'area', $area_where);

        switch (count($_tmp))
        {
            case 1:
                $_tmp['province'] = $_tmp[0]['area_name'];
                $_tmp['city']     = '';
                $_tmp['district'] = '';
                unset($_tmp[0]);
                break;

            case 2:
                $_tmp['province'] = $_tmp[0]['area_name'];
                $_tmp['city']     = $_tmp[1]['area_name'];
                $_tmp['district'] = '';
                unset($_tmp[0], $_tmp[1]);
                break;

            case 3:
                $_tmp['province'] = $_tmp[0]['area_name'];
                $_tmp['city']     = $_tmp[1]['area_name'];
                $_tmp['district'] = $_tmp[2]['area_name'];
                unset($_tmp[0], $_tmp[1], $_tmp[2]);
                break;
        }

        return $_tmp;
    }

    /**
     * [getAreaIDByPCD 根据省市县地区获得真正地区ID]
     * @param  [int] $p_district [县ID]
     * @param  [int] $p_city     [市ID]
     * @param  [int] $p_province [省ID]
     * @return [int]             [地区ID]
     * @author [string]          [NYJ]
     */
    protected function getAreaIDByPCD($p_district = null, $p_city = null, $p_province = null)
    {
        $tmp_areaID = 110000;
        if ($p_district) {
            $tmp_areaID = $p_district;
        } else if ($p_city) {
            $tmp_areaID = $p_city;
        } else {
            $tmp_areaID = $p_province;
        }

        return $tmp_areaID;
    }

    /**
     * [申请列表]
     * @return [type] [筛选条件，显示]
     * @author [NYJ]
     */
    public function index($p = 1)
    {

        $p        = intval($p) > 0 ? $p : 1;
        $user     = M('user u');
        $pagesize = 15;#每页数量
        $offset   = $pagesize * ($p - 1);//计算记录偏移量

        $adminInfo = session('adminInfo');

        $where = '1 = 1';

        if (I('get.aid', -1, 'intval') <> -1)
        {
            if (I('get.aid', -1, 'intval') == 0) {

                $where .= ' and  aid =0';
            } else {
                $where .= ' and aid=' . I('get.aid', 0, 'intval');
            }
        }
        $where .= I('get.user_name') != '' ? ' and u.user_name like "%' . I('get.user_name') . '%"' : '';
        $where .= I('get.telephone') != '' ? ' and u.telephone = ' . I('get.telephone') : '';
        $where .= I('get.create_time_beg') != '' ? ' and u.create_time >= ' . strtotime(I('get.create_time_beg')) : '';
        $where .= I('get.create_time_end') != '' ? ' and u.create_time < ' . strtotime(I('get.create_time_end')) : '';
        $where .= I('get.status') != '' && I('get.status') != -1 ? ' and u.status=' . I('get.status') : '';

        if ($adminInfo['gpid'])
        {
            $is_work = M('group')->where('id='.$adminInfo['gpid'])->getField('work_status');;

            if ($is_work != 0)
            {
                $where .= ' and u.gpid=' . session('adminInfo.gpid');
            }
        }

        if (session('adminInfo.remark') == '业务员')
        {
            $where .= ' and u.admin_id=' . session('adminInfo.id');
        }

        $nOrder = I('get.order');
        switch ($nOrder)
        {
            case 1:
                $_order = 'CONVERT(u.user_name USING gbk)';
                break;

            case 2:
                $_order = 'CONVERT(u.user_name USING gbk) desc';
                break;

            case 3:
                $_order = 'u.identity_no';
                break;

            case 4:
                $_order = 'u.identity_no desc';
                break;

            case 5:
                $_order = 'CONVERT(b.bank_name USING gbk)';
                break;

            case 6:
                $_order = 'CONVERT(b.bank_name USING gbk) desc';
                break;
            case 7:
                $_order = 'CONVERT(u.department_name USING gbk)';
                break;
            case 8:
                $_order = 'CONVERT(u.department_name USING gbk) desc';
                break;

            default:
                $_order = 'u.entry_no desc';
                break;
        }

        $count = $user->join('join app_bank b on b.id = u.loan_bank_id')->where($where)->count();
        $list  = $user->field('u.*,b.bank_short_name')->join('app_bank b on b.id = u.loan_bank_id')->where($where)->order($_order)->limit($offset . ',' . $pagesize)->select();
        $page  = new \Think\Page($count, $pagesize);
        $page  = $page->show();

        foreach ($list as $key => $value)
        {
            if ($value['gpid'])
            {
                $group = $this->getInfo('*', 'group', 'id=' . $value['gpid']);
                $list[$key]['group_name'] = $group['name'];
            }
        }

        $bankList = $this->getList('*', 'bank', null, 'id desc');

        $this->assign('bankList', $bankList);
        $this->assign('list', $list);
        $this->assign('page', $page);
        $this->assign('statusItems', $this->statusItems);
        $this->display();
    }

    public function commission()
    {
        //codition【状态为完成，当前部门，日期是当月之前所有】

        $arrWhere = ['u.check_status' => 29, 'u.gpid' => session('adminInfo.gpid')];
        $beginThismonth = mktime(0, 0, 0, date('m'), 1, date('Y'));
        $arrWhere['u.create_time'] = array('lt', $beginThismonth);


        if (session('adminInfo.gpid')) {
            $nGroup_id = session('adminInfo.gpid');
        } else {
            $nGroup_id = session('adminInfo.gid');
        }

        $_groupInfo = $this->getInfo('*', 'group_info', ['group_id' => $nGroup_id]);

        $retCommisionList = $this->getList('u.*,b.bank_short_name', 'user u', $arrWhere, 'count(u.id)', true, ' join app_bank b on b.id = u.loan_bank_id');

        /*返佣费率=费率-银行费率-票据成本-结算费率
            app_car_info.company_rate - app_car_info.bank_rate - app_group_info.ticket_cost -app_group_info.settle_rate
      返佣=（返佣费率-渠道风险拨备比例）*比例*销售价格
          (返佣费率 - app_group_info.place_risk_ratio) * app_group_info.ratio * app_car_info.sale_price
      */

        foreach ($retCommisionList as &$_user)
        {
            $_carInfo = $this->getInfo('*', 'car_info', ['user_id' => $_user['id']]);

            $_tmpCRate = $_carInfo['company_rate'] - $_carInfo['bank_rate'] - $_groupInfo['ticket_cost'] - $_groupInfo['settle_rate'];

            $_tmpCQuota = ($_tmpCRate - $_groupInfo['place_risk_ratio']) * $_groupInfo['ratio'] * $_carInfo['sale_price'];

            $_user['commission'] = $_tmpCQuota;
        }

        $this->assign('list', $retCommisionList);
        $this->display();
    }

    //申请已待定
    public function wait_status()
    {
        $list = $this->getStatus('=9)');
        $this->assign('list', $list);
        $this->display();
    }

    //申请待提交
    public function wait_submit()
    {
        $list = $this->getStatus('=1)', '=-1');
        $this->assign('list', $list);
        $this->display();
    }

    //申请待审核
    public function wait_check()
    {
        $list = $this->getStatus('=1)', '>-1 and check_status<6');
        $this->assign('list', $list);
        $this->display();
    }

    public function modifyBank()
    {
        if (IS_POST) {
            $nUserId = $_POST['user_id'];
            $nBankId = $_POST['bank_id'];

            $_tmpUser = $this->getInfo('check_status,loan_bank_id', 'user', ['id' => $nUserId]);

            if($nBankId==$_tmpUser['loan_bank_id']){
                $tips = ['message' => '更改的银行与原银行相同，不执行操作'];
                echo json_encode($tips);
            }
            else{
                if ($_tmpUser['check_status'] <= 6) {
                    echo $this->updateData(['loan_bank_id' => $nBankId, 'check_status' => -4], 'user', 2, ['id' => $nUserId]);
                } else {
                    $tips = ['message' => '该客户已经提交终审，不能更改银行', 'status' => 0];
                    echo json_encode($tips);
                }
            }
            exit();
        }
    }

    // 表单校验
    public function validate()
    {
        if (IS_POST) {
            $id = M('user')->where(array('identity_no' => $_POST['identity_no'], 'status' => array('lt', 3)))->getField('id');
            if ($id > 0) {
                return $this->ajaxReturn(array('status' => -1, 'info' => '身份证号已经存在,录入失败'));
            }
            $identity_no = trim($_POST['identity_no']);
            // 身份证有效判断

            $IDInfo = self::getIDCardInfo($identity_no);
            if ($IDInfo['error'] != 2) {
                return $this->ajaxReturn(array('status' => -1, 'info' => '请输入有效的身份证号'));
            }

            // 性别判断
            if ($IDInfo['sexFlag'] % 2 == 0) {
                $nSex = 2;
            } else {
                $nSex = 1;
            }

            $spouse_name = trim($_POST['spouse_name']);

            // 配偶存在
            if (!empty($spouse_name)) {
                $spouse_identity_no = trim(I('post.spouse_identity_no'));

                $spouseIDInfo = self::getIDCardInfo($spouse_identity_no);

                if ($spouseIDInfo['error'] != 2) {
                    return $this->ajaxReturn(array('status' => -1, 'info' => '请输入有效的配偶身份证号'));
                }

                $nSpouseSex = $spouseIDInfo['sexFlag'] % 2 == 0 ? 2 : 1;

                if ($nSex == $nSpouseSex) {
                    return $this->ajaxReturn(array('status' => -1, 'info' => '请确认您配偶性别是否正确'));
                }
            }

            return $this->ajaxReturn(array('status' => 0, 'info' => 'ok'));
        }
    }

    // 编辑详情
    public function editBase()
    {
        if (IS_POST)
        {
            $identity_no = trim(I('post.identity_no'));
            // 身份证有效判断

            $IDInfo = self::getIDCardInfo($identity_no);

            if ($IDInfo['error'] != 2) {
                return $this->error('请输入有效的身份证号');
            }

            // 性别判断
            if ($IDInfo['sexFlag'] % 2 == 0) {
                $nSex = 2;
            } else {
                $nSex = 1;
            }

            $_POST['birth_year_month'] = $IDInfo['tdate'];
            $_POST['sex'] = $nSex;
            $_POST['age'] = $IDInfo['age'];
            $_POST['update_time'] = time();

            $spouse_name = trim(I('post.spouse_name'));

            // 配偶存在
            if (!empty($spouse_name)) {
                $spouse_identity_no = trim(I('post.spouse_identity_no'));

                $spouseIDInfo = self::getIDCardInfo($spouse_identity_no);

                if ($spouseIDInfo['error'] != 2) {
                    return $this->error('请输入有效的配偶身份证号');
                }

                $nSpouseSex = $spouseIDInfo['sexFlag'] % 2 == 0 ? 2 : 1;

                if ($nSex == $nSpouseSex) {
                    return $this->error('请确认您配偶性别是否正确');
                }
            } else {
                unset($_FILES['spouse_id_photo_pros'], $_FILES['spouse_id_photo_cons'], $_FILES['spouse_credit_up'], $_FILES['spouse_credit_down']);
            }

            // 无担保人，清除图片
            $assure_name = trim(I('post.assure_name'));
            if (empty($assure_name)) {
                unset($_FILES['assure_id_photo_pros'], $_FILES['assure_id_photo_cons']);
            } else {
                $assure_data = [
                    'user_name' => $_POST['assure_name'],
                    'identity_no' => $_POST['assure_identity_no'],
                    'create_time' => time(),
                    'update_time' => time()
                ];
            }
//            print_r($_FILES);die;
            include VENDOR_PATH . 'aliyunOss/autoload.php';
//            $_POST['identity_photo_pros']          = $this->uploadAliyunOss('identity_photo_pros');
//            $_POST['identity_photo_cons']          = $this->uploadAliyunOss('identity_photo_cons');
//            $_POST['credit_authorize_photo']       = $this->uploadAliyunOss('credit_authorize_photo');
//            $_POST['credit_authorize_up']          = $this->uploadAliyunOss('credit_authorize_up');

            if($_FILES['identity_photo_pros']['tmp_name'] != '')
            {
                $_POST['identity_photo_pros'] = $this->uploadAliyunOss('identity_photo_pros');
            }
            if($_FILES['identity_photo_cons']['tmp_name'] != '')
            {
                $_POST['identity_photo_cons'] = $this->uploadAliyunOss('identity_photo_cons');
            }
            if($_FILES['credit_authorize_photo']['tmp_name'] != '')
            {
                $_POST['credit_authorize_photo'] = $this->uploadAliyunOss('credit_authorize_photo');
            }
            if($_FILES['credit_authorize_up']['tmp_name'] != '')
            {
                $_POST['credit_authorize_up'] = $this->uploadAliyunOss('credit_authorize_up');
            }
            if($_FILES['table_credit_photo']['tmp_name'] != '')
            {
                $_POST['table_credit_photo'] = $this->uploadAliyunOss('table_credit_photo');
            }
            if($_FILES['spouse_id_photo_pros']['tmp_name'] != '')
            {
                $_POST['spouse_id_photo_pros'] = $this->uploadAliyunOss('spouse_id_photo_pros');
            }
            if($_FILES['spouse_id_photo_cons']['tmp_name'] != '')
            {
                $_POST['spouse_id_photo_cons'] = $this->uploadAliyunOss('spouse_id_photo_cons');
            }
            if($_FILES['spouse_credit_photo']['tmp_name'] != '')
            {
                $_POST['spouse_credit_photo'] = $this->uploadAliyunOss('spouse_credit_photo');
            }
            if($_FILES['spouse_credit_up']['tmp_name'] != '')
            {
                $_POST['spouse_credit_up'] = $this->uploadAliyunOss('spouse_credit_up');
            }


            $adminInfo=session('adminInfo');
            $nUserId = $_POST['user_id'];
            unset($_POST['user_id']);
            // 修改信息
            $_checkLogData = ['user_id' =>$nUserId, 'type' => session('adminInfo.group_name'),'opinion' => '重新提交客户征信', 'check_status' => -5, 'admin_id' => session('adminInfo.id'), 'admin_name' => session('adminInfo.name'), 'add_time' => time()];
            $_new_checkLog = $this->updateData($_checkLogData, 'check_log');
            $retUpdate = $this->updateData($_POST, 'user', 2, 'id = ' . $nUserId);
            if ($retUpdate) {
                $this->redirect('Apply/index');
            }
        }

    }

    public function addAssure()
    {
        if (IS_POST)
        {
            $nUserId = $_POST['user_id'];
            $strIDNO = $_POST['identity_no'];

            $nBegTime = strtotime(date('Y-m-01 00:00:00'));
            $nEndTime = strtotime(date('Y-m-d h:i:s'));

            $where['create_time'] = [['gt', $nBegTime], ['lt', $nEndTime], 'and'];
            $where['identity_no'] = ['EQ', $strIDNO];

            $CardID = self::getIDCardInfo($strIDNO);

            $id = M('assure')->where($where)->getField('id');
            if (!is_null($id)) {
                return $this->error('担保人一个月两次征信，不允许添加');
            }

            include VENDOR_PATH . 'aliyunOss/autoload.php';
            $_POST['assure_id_photo_pros'] = $this->uploadAliyunOss('assure_id_photo_pros');
            $_POST['assure_id_photo_cons'] = $this->uploadAliyunOss('assure_id_photo_cons');
            $_POST['assume_credit_photo']  = $this->uploadAliyunOss('assume_credit_photo');
            $_POST['credit_up_photo']      = $this->uploadAliyunOss('credit_up_photo');



            $_POST['create_time'] = time();
            $_POST['update_time'] = time();
            $_POST['age']=$CardID['age'];

            $data['status'] = 1;

            $result = $this->updateData($data, 'user', 2, 'id=' . $nUserId);
            $ret = $this->updateData($_POST, 'assure');

            if ($ret) {
                $this->success('添加成功', U('Apply/index'));
            } else {
                $this->error('添加失败，联系管理员');
            }

        }
        $this->display();
    }

    /*信息录入*/
    public function add()
    {
        if(I('post.btn')){$this->success('');}
        if (IS_POST)
        {
            $id = M('user')->where(array('identity_no' => I('post.identity_no'), 'status' => array('lt', 3)))->getField('id');
            if ($id > 0) {
                return $this->ajaxReturn(array('status' => -1, 'info' => '身份证号已经存在,录入失败'));
            }

            $identity_no = trim(I('post.identity_no'));
            // 身份证有效判断

            $IDInfo = self::getIDCardInfo($identity_no);

            if ($IDInfo['error'] != 2) {
                return $this->ajaxReturn(array('status' => -1, 'info' => '请输入有效的身份证号'));
            }

            // 性别判断
            if ($IDInfo['sexFlag'] % 2 == 0)
            {
                $nSex = 2;
            } else {
                $nSex = 1;
            }

            $admin_id = session('adminInfo.id');//业务员id

            if (session('adminInfo.gpid'))
            {
                $_gVal = $this->getInfo('id,name', 'group', 'id = ' . session('adminInfo.gpid'));
                $_POST['department_name'] = $_gVal['name'];

            } else {
                $_POST['department_name'] = session('adminInfo.group_name');
            }

            if (session('adminInfo.gpid'))
            {
                $nGpid = session('adminInfo.gpid');
            } else {
                $nGpid = session('adminInfo.gid');
            }

            $_POST['gpid'] = $nGpid;

            $_POST['birth_year_month'] = $IDInfo['tdate'];
            $_POST['sex']              = $nSex;
            $_POST['age']              = $IDInfo['age'];
            $_POST['admin_id']         = $admin_id;
            $_POST['create_time']      = time();
            $_POST['update_time']      = time();
            // 客户编号：日期+部门编号+业务员编号+数量；如：20170504001002013
            $stEntryNo = date('Ymd') . session('adminInfo.gid') . session('adminInfo.id');//getRandomString(20);

            $spouse_name = trim(I('post.spouse_name'));

            include VENDOR_PATH . 'aliyunOss/autoload.php';
            // 配偶存在
            if (!empty($spouse_name))
            {
                $spouse_identity_no  = trim(I('post.spouse_identity_no'));

                $spouseIDInfo        = self::getIDCardInfo($spouse_identity_no);

                $_POST['spouse_age'] = $spouseIDInfo['age'];

                if($_FILES['spouse_id_photo_pros']['tmp_name'] != '')
                {
                    $_POST['spouse_id_photo_pros'] = $this->uploadAliyunOss('spouse_id_photo_pros');
                }

                if($_FILES['spouse_id_photo_cons']['tmp_name'] != '')
                {
                    $_POST['spouse_id_photo_cons'] = $this->uploadAliyunOss('spouse_id_photo_cons');
                }

                if($_FILES['spouse_credit_photo']['tmp_name'] != '')
                {
                    $_POST['spouse_credit_photo'] = $this->uploadAliyunOss('spouse_credit_photo');
                }

                if($_FILES['spouse_credit_up']['tmp_name'] != '')
                {
                    $_POST['spouse_credit_up'] = $this->uploadAliyunOss('spouse_credit_up');
                }

                if ($spouseIDInfo['error'] != 2) {
                    return $this->ajaxReturn(array('status' => -1, 'info' => '请输入有效的配偶身份证号'));
                }

                $nSpouseSex = $spouseIDInfo['sexFlag'] % 2 == 0 ? 2 : 1;

                if ($nSex == $nSpouseSex) {
                    return $this->ajaxReturn(array('status' => -1, 'info' => '请确认您配偶性别是否正确'));
                }
            } else {
                unset($_FILES['spouse_id_photo_pros'], $_FILES['spouse_id_photo_cons'], $_FILES['spouse_credit_up'], $_FILES['spouse_credit_down']);
            }

            // 无担保人，清除图片
            $assure_name = trim(I('post.assure_name'));
            if (empty($assure_name)) {
                unset($_FILES['assure_id_photo_pros'], $_FILES['assure_id_photo_cons']);
            }

            $_POST['identity_photo_pros']          = $this->uploadAliyunOss('identity_photo_pros');
            $_POST['identity_photo_cons']          = $this->uploadAliyunOss('identity_photo_cons');
            $_POST['credit_authorize_photo']       = $this->uploadAliyunOss('credit_authorize_photo');
            $_POST['credit_authorize_up']          = $this->uploadAliyunOss('credit_authorize_up');

            if($_FILES['table_credit_photo']['tmp_name'] != '')
            {
                $_POST['table_credit_photo'] = $this->uploadAliyunOss('table_credit_photo');
            }

            // 身份真实性验证(征信接口)
            $pr_data["name"]      = $_POST['user_name'];  // 姓名,必填
            $pr_data["id_number"] = $_POST['identity_no'];  // 身份证号,必填
            $pr_data["mobile"]    = $_POST['telephone'];  // 手机号,必填

            $ret = RequestController::pre_loan_apply($pr_data);

            if ($ret['success']) {
                $_POST['report_id'] = $ret['report_id'];
            }


            $newUserId = M('user')->add($_POST);
            //$newUserId = $this->updateData($_POST, 'user');
            if ($newUserId)
            {
                // 插入申请记录
                $newUser = $this->getInfo('id,department_name,status,admin_id', 'user', ['identity_no' => $identity_no]);

                // 业务类型,车辆性质，上牌类型
                $this->updateData(['business_type' => $_POST['business_type'], 'models_form' => $_POST['models_form'], 'license_type' => $_POST['license_type'], 'user_id' => $newUser['id'], 'create_time' => time()],
                    'car_info');

                $this->updateData(['entry_no' => $stEntryNo . $newUser['id']], 'user', 2, 'id = ' . $newUser['id']);

                $_new_apply_pro = $this->updateData(
                    ['user_id' => $newUser['id'], 'create_time' => time(), 'update_time' => time()], 'apply_progress');

                // $assure_data['user_id'] = $newUser['id'];
                // $_new_assure = $this->updateData($assure_data,'assure');

                $_checkLogData = ['user_id' => $newUser['id'], 'type' => $newUser['department_name'], 'status' => $newUser['status'],'opinion'=>'提交新客户', 'check_status' => -5, 'admin_id' => $admin_id, 'admin_name' => session('adminInfo.name'), 'add_time' => time()];
                $_new_checkLog = $this->updateData($_checkLogData, 'check_log');
//				// 文件处理开始
//				// 文件处理end
                $this->success('添加成功', U('Apply/index'));
            } else {
                return $this->error('添加失败');
            }
        }

        $tmpBids = session('adminInfo.bids');

        if (empty($tmpBids) || is_null($tmpBids))
        {
            $bankList = $this->getList('*', 'bank', '1 = 1', 'id desc');
        }else {
            $bankList = $this->getList('*', 'bank', 'id in ('.session('adminInfo.bids').')', 'id desc');
        }

        $this->assign('bankList', $bankList);
        $this->assign('businessTypes', $this->carFirmItems);
        $this->assign('onCardItems', $this->onCardItems);
        $this->assign('carModelItems', $this->carModelItems);
        $this->display();
    }

/*    public function abc(){
        $adminInfo = session('adminInfo.group_name');
        print_r($adminInfo);
        exit;
    }*/


    /*信息修改或编辑*/
    public function edit()
    {
        if (IS_POST)
        {
            // 文件处理开始
            $nUserId = $_POST['user_id'];
            $info = $this->getInfo('u.spouse_name,u.loan_bank_id,ci.business_type,ci.models_form,ci.license_type', 'user u', 'u.id=' . $nUserId, 'app_car_info as ci on u.id = ci.user_id');

            $assureList = $this->getList('id,user_name,identity_no', 'assure', ['user_id' => $nUserId], '');
            if (!is_null($info))
            {
                $strWhere = 'business_type = ' . $info['business_type'] . ' and bank_id = ' . $info['loan_bank_id'] . ' and models_form = ' . $info['models_form'] . ' and license_type = ' . $info['license_type'] .' and ( file_type=0 ';
                if ($assureList != null) {
                    $strWhere .= ' or file_type=2';
                }
                if ($info['spouse_name'] != null) {
                    $strWhere .= ' or file_type=1';
                }
                $strWhere .= ')';
                $needUploadFiles = $this->getList('*', 'file_set', $strWhere, 'id desc');
                foreach ($needUploadFiles as $_v)
                {
                    $extend=pathinfo($_POST[$_v['e_file_key']]);
                    if( $extend['filename'] == null )
                    {

                    }
                    else
                    {
                        if ($extend['extension'] == 'mp4')
                        {
                            $_tmpUserFileData = ['user_id' => $nUserId, 'file_key' => $_v['file_key'], 'e_file_key' => $_v['e_file_key'], 'file_dist' => $_POST[$_v['e_file_key']], 'is_pic' => '0   ', 'create_time' => time()];
                        } else {
                            $_tmpUserFileData = ['user_id' => $nUserId, 'file_key' => $_v['file_key'], 'e_file_key' => $_v['e_file_key'], 'file_dist' => $_POST[$_v['e_file_key']], 'is_pic' => '1', 'create_time' => time()];
                        }

                        $_checkFile = 'user_id = ' . $nUserId . ' and e_file_key = "' . $_v['e_file_key'] . '"';

                        $_tmpFile = $this->getInfo('id', 'user_file', $_checkFile);

                        if (is_null($_tmpFile)) {
                            $this->updateData($_tmpUserFileData, 'user_file');
                        } else {
                            $this->updateData($_tmpUserFileData, 'user_file', 2, $_checkFile);
                        }
                    }
                }
            }

            // 文件处理end

            $_POST['company_tel'] = $_POST['area_code'] . '-' . $_POST['company_tel'];
            unset($_POST['area_code']);

            $_POST['home_area_id'] = $this->getAreaIDByPCD($_POST['home_district'], $_POST['home_city'], $_POST['home_province']);
            $_POST['now_area_id'] = $this->getAreaIDByPCD($_POST['now_district'], $_POST['now_city'], $_POST['now_province']);
            $_POST['company_area_id'] = $this->getAreaIDByPCD($_POST['district'], $_POST['city'], $_POST['province']);

            $_POST['spouse_area_id'] = $this->getAreaIDByPCD($_POST['spouse_home_district'], $_POST['spouse_home_city'], $_POST['spouse_home_province']);
            $_POST['spouse_company_area_id'] = $this->getAreaIDByPCD($_POST['spouse_company_district'], $_POST['spouse_company_city'], $_POST['spouse_company_province']);

            $sub_type=$_POST['sub-type'];
            $_POST['gpid'] = session('adminInfo.gpid');
            $user_info = $this->getInfo('*', 'user', 'id=' . $nUserId);
            if($sub_type==2){

            }
            if($sub_type==1){
                if ($user_info['status'] == 9) {
                    $_POST['status'] = 1;
                }
                if ($user_info['status'] == 12 || $user_info['status'] == 1) {
                    $_POST['status'] = 1;
                    $_POST['check_status'] = 0;
                }
            }

            $result = $this->updateData($_POST, 'user', 2, 'id= ' . $nUserId);

            // 垫资信息
            $checkExistAdvance = $this->getList('id', 'advance_info', 'user_id = ' . $nUserId, 'id desc');
            $dataAdvanceInfo = [
                'server_fee' => $_POST['server_fee']
                , 'mortgage_fee' => $_POST['mortgage_fee']
                , 'performance_fee' => $_POST['performance_fee']
                , 'card_on_deposit' => $_POST['card_on_deposit']
                , 'guarantee_fee' => $_POST['guarantee_fee']
                , 'card_on_fee' => $_POST['card_on_fee']
                , 'counter_fee' => $_POST['counter_fee']
                , 'assess_fee' => $_POST['assess_fee']
                , 'gps_fee' => $_POST['gps_fee']
                , 'liability_insurance' => $_POST['liability_insurance']
                , 'finance_safe_fee' => $_POST['finance_safe_fee']
                , 'finance_buy_fee' => $_POST['finance_buy_fee']
                , 'finance_decorate_fee' => $_POST['finance_decorate_fee']
                , 'other_fee' => $_POST['other_fee']
                , 'total_fee' => $_POST['total_fee']
                , 'update_time' => time()
            ];

            if (empty($checkExistAdvance)) {
                $dataAdvanceInfo['user_id'] = $nUserId;
                $dataAdvanceInfo['create_time'] = time();

                $newAdvance = $this->updateData($dataAdvanceInfo, 'advance_info', 1);
            } else {
                $modAdvance = $this->updateData($dataAdvanceInfo, 'advance_info', 2, 'id = ' . $_POST['advance_id']);
            }

            // 车辆信息
            $checkCarInfo = $this->getList('id', 'car_info', 'user_id = ' . $nUserId, 'id desc');
            $dataCarInfo = [
                // 'business_type'              => $_POST['business_type']
                'car_type' => $_POST['car_type']
                , 'models_form' => $_POST['models_form']
                , 'brand_id' => $_POST['brand_id']
                , 'car_series_id' => $_POST['car_series_id']
                , 'car_form_id' => $_POST['car_form_id']
                , 'seat_no' => $_POST['seat_no']
                , 'guide_price' => $_POST['guide_price']
                , 'sale_price' => $_POST['sale_price']
                , 'license_area' => $_POST['license_area']
                , 'license_type' => $_POST['license_type']
                , 'driving_license' => $_POST['driving_license']
                , 'term' => $_POST['term']
                , 'month_repayment' => $_POST['month_repayment']
                , 'repayment_total' => $_POST['repayment_total']
                , 'company_rate' => $_POST['company_rate']
                , 'small_rate' => $_POST['small_rate']
                , 'sign_first_payment' => $_POST['sign_first_payment']
                , 'real_first_payment' => $_POST['real_first_payment']
                , 'real_loan_proportion' => $_POST['real_loan_proportion']
                , 'sign_first_pay_proportion' => $_POST['sign_first_pay_proportion']
                , 'real_first_pay_proportion' => $_POST['real_first_pay_proportion']
                , 'sign_loan_quota' => $_POST['sign_loan_quota']
                , 'sign_loan_proportion' => $_POST['sign_loan_proportion']
                , 'commission' => $_POST['commission']
                , 'car_dealer' => $_POST['car_dealer']
                , 'person' => $_POST['person']
                , 'real_loan_quota' => $_POST['real_loan_quota']
//                , 'real_loan_proportion' => $_POST['real_loan_proportion']
                , 'bank_rate' => $_POST['bank_rate']
                , 'car_dealer_commission' => $_POST['car_dealer_commission']
                , 'update_time' => time()
            ];

            if (empty($checkCarInfo)) {
                $dataCarInfo['user_id'] = $nUserId;
                $dataCarInfo['create_time'] = time();

                $_license = $this->getInfo('is_province', 'license', ['address_name' => $_POST['license_area']]);

                // 根据贷款银行+车辆性质+上牌地（省内外），锁定银行规则利率
                $_where = ['bank_id' => $info['loan_bank_id'], 'car_model' => $_POST['models_form'],
                    'is_province' => $_license['is_province'], 'year_limit' => $_POST['term']
                ];
                $_bankRule = $this->getInfo('rate', 'bank_rule', $_where);
                $dataCarInfo['bank_rate'] = $_bankRule['rate'];

                $newCarInfo = $this->updateData($dataCarInfo, 'car_info', 1);
            } else {
                $modCarInf = $this->updateData($dataCarInfo, 'car_info', 2, 'id = ' . $_POST['car_info_id']);
            }

            // 紧急联系人|| 如果有记录是修改，没有记录则新增
            $checkExist = $this->getList('id', 'emergency_contact', 'user_id = ' . $nUserId, 'id desc');
            if (empty($checkExist)) {
                $Emergency = M("emergency_contact");
                $emergencyContactors[] = array('user_id' => $nUserId, 'user_name' => $_POST['urgent_user_name1'], 'telephone' => $_POST['urgent_tel1'], 'relationship' => $_POST['relationship1'], 'create_time' => time(), 'update_time' => time());
                $emergencyContactors[] = array('user_id' => $nUserId, 'user_name' => $_POST['urgent_user_name2'], 'telephone' => $_POST['urgent_tel2'], 'relationship' => $_POST['relationship2'], 'create_time' => time(), 'update_time' => time());
                $Emergency->addAll($emergencyContactors);
            } else {
                $mod1 = $this->updateData(
                    array('user_name' => $_POST['urgent_user_name1'], 'telephone' => $_POST['urgent_tel1'], 'relationship' => $_POST['relationship1'], 'update_time' => time()),
                    'emergency_contact', 2, 'id= ' . $_POST['urgent_id1']);

                $mod22 = $this->updateData(
                    array('user_name' => $_POST['urgent_user_name2'], 'telephone' => $_POST['urgent_tel2'], 'relationship' => $_POST['relationship2'], 'update_time' => time()),
                    'emergency_contact', 2, 'id= ' . $_POST['urgent_id2']);
            }

//            if($sub_type==2){
//                $_checkLogData = ['user_id' => $nUserId, 'type' => session('adminInfo.group_name'), 'status' => 1,'opinion' => '保存客户信息', 'check_status' => -1, 'admin_id' => session('adminInfo.id'), 'admin_name' => session('adminInfo.name'), 'add_time' => time()];
//            }
            if($sub_type==1) {
                $_checkLogData = ['user_id' => $nUserId, 'type' => session('adminInfo.group_name'), 'status' => 1, 'check_status' => -1,'opinion' => '提交客户信息', 'admin_id' => session('adminInfo.id'), 'admin_name' => session('adminInfo.name'), 'add_time' => time()];
            }


            $_new_checkLog = $this->updateData($_checkLogData, 'check_log');

            $this->success('提交完成', U('Apply/detail_info?user_id=' . $nUserId));
        } else {
            $userInfo = $this->getInfo('*', 'user', 'id=' . I('get.user_id', 0, 'intval'));
            $carInfo  = $this->getInfo('*','car_info','user_id=' . I('get.user_id', 0, 'intval'));
            $this->assign('userInfo', $userInfo);
            $bankList = $this->getList('*', 'bank', null, 'id desc');
            $this->assign('bankList', $bankList);
            $groupList = $this->getList('id,name', 'group', 'status = 1', 'id desc');
            $this->assign('bankList', $bankList);
            $this->assign('businessTypes', $this->carFirmItems);
            $this->assign('onCardItems', $this->onCardItems);
            $this->assign('carModelItems', $this->carModelItems);
            $this->assign('groupList', $groupList);
            $this->assign('carInfo', $carInfo);
            $this->display();
        }
    }

    /**
     * 删除信息（逻辑删除）
     */
    public function del()
    {
        $result = M('user')->where('id=' . I('get.id', 0, 'intval'))->setField('status', 3);
        // $result = $this->deleteData('id=' . I('get.id', 0, 'intval'), 'admins');
        $this->returnResult($result);
    }

    /**
     * [描述 从身份证中提取信息,包括15位和18位身份证]
     * @param  [$IDCard] 给定某身份证号
     * @return [type] 该身份证包含的用户信息
     * @author [NYJ] <[<3466309582qq.com>]>
     */
    static function getIDCardInfo($IDCard)
    {
        $result['error'] = 0;//0：未知错误，1：身份证格式错误，2：无错误
        $result['flag'] = '';//0标示成年，1标示未成年
        $result['tdate'] = '';//生日，格式如：2012-11-15
        if (!preg_match("/^(\d{15}$|^\d{18}$|^\d{17}(\d|X|x))$/", $IDCard)) {
            $result['error'] = 1;
            return $result;
        } else {
            if (strlen($IDCard) == 18) {
                $sexFlag = substr($IDCard, -2, 1);//单数男 双数女
                $tyear = intval(substr($IDCard, 6, 4));
                $tmonth = intval(substr($IDCard, 10, 2));
                $tday = intval(substr($IDCard, 12, 2));
                if ($tyear > date("Y") || $tyear < (date("Y") - 100)) {
                    $flag = 0;
                } else if ($tmonth < 0 || $tmonth > 12) {
                    $flag = 0;
                } else if ($tday < 0 || $tday > 31) {
                    $flag = 0;
                } else {
                    $tdate = $tyear . "-" . $tmonth . "-" . $tday . " 00:00:00";
                    $result['tdate'] = $tyear . "-" . $tmonth . "-" . $tday;
                    if ((time() - mktime(0, 0, 0, $tmonth, $tday, $tyear)) > 18 * 365 * 24 * 60 * 60) {
                        $flag = 0;
                    } else {
                        $flag = 1;
                    }
                }
            } else if (strlen($IDCard) == 15) {
                $sexFlag = substr($IDCard, -1);//单数男 双数女
                $tyear = intval("19" . substr($IDCard, 6, 2));
                $tmonth = intval(substr($IDCard, 8, 2));
                $tday = intval(substr($IDCard, 10, 2));
                if ($tyear > date("Y") || $tyear < (date("Y") - 100)) {
                    $flag = 0;
                } else if ($tmonth < 0 || $tmonth > 12) {
                    $flag = 0;
                } else if ($tday < 0 || $tday > 31) {
                    $flag = 0;
                } else {
                    $tdate = $tyear . "-" . $tmonth . "-" . $tday . " 00:00:00";
                    $result['tdate'] = $tyear . "-" . $tmonth . "-" . $tday;
                    if ((time() - mktime(0, 0, 0, $tmonth, $tday, $tyear)) > 18 * 365 * 24 * 60 * 60) {
                        $flag = 0;
                    } else {
                        $flag = 1;
                    }
                }
            }
        }
        $result['error'] = 2;//0：未知错误，1：身份证格式错误，2：无错误
        $result['isAdult'] = $flag;//0标示成年，1标示未成年
        $result['flag'] = $flag;//0标示成年，1标示未成年
        $result['birthday'] = $tdate;//生日日期
        $result['sexFlag'] = $sexFlag;//生日日期
        $result['age'] = date("Y") - $tyear;//生日日期
        return $result;
    }

    //征信待提交
    public function credit()
    {


        $list = $this->getStatus('!=0)', '=-5');
        $this->assign('list', $list);
        $this->display();
    }

    //征信待审核
    public function credit_waitCheck()
    {
        $list = $this->getStatus('!=0)', '=-4');
        $this->assign('list', $list);
        $this->display();
    }

    //申请已退回
    public function Returns()
    {
        $list = $this->getStatus('=12)','<=6');
        $this->assign('list', $list);
        $this->display();
    }

    //申请拒绝列表
    public function refuse()
    {
        $list = $this->getStatus('=5)');
        $this->assign('list', $list);
        $this->display();
    }

    public function refuse_info()
    {
        $info = $this->getInfo('*', 'check_log', 'user_id=' . $_POST['id'] . ' and status=0 and refuse_type=4');
        $this->returnResult($info, null, null, $info);
    }

    //业务进度详情
    public function check_info()
    {
        $info = $this->getInfo('*', 'check_log', 'id=' . $_POST['id']);
        $info['refuse_name'] = $info['refuse_type'];
        $info['refuse_reason'] = $info['opinion'];
        // switch ($info['refuse_type'])
        // {
        // 	case '1':
        // 		$info['refuse_name']='追加保证金';
        // 		break;
        // 	case '2':
        // 		$info['refuse_name']='追加担保人';
        // 		break;
        // 	case '3':
        // 		$info['refuse_name']='提高首付';
        // 		break;
        // 	case '4':
        // 		$info['refuse_name']='拒贷';
        // 		break;
        // 	default:
        // 	    $info['refuse_name']='没有该类型';
        // 		break;
        // }

        $this->returnResult($info, null, null, $info);
    }

    public function getStatus($status = null, $check_status = null)
    {
        $where = '1 = 1';
        if (I('get.aid', -1, 'intval') <> -1) {
            if (I('get.aid', -1, 'intval') == 0) {
                $where .= ' and  aid =0';
            } else {
                $where .= ' and aid=' . I('get.aid', 0, 'intval');
            }
        }
        $where .= I('get.user_name') != '' ? ' and user_name like "%' . I('get.user_name') . '%"' : '';

        $where .= I('get.telephone') != '' ? ' and telephone = ' . I('get.telephone') : '';

        $where .= I('get.create_time_beg') != '' ? ' and create_time >= ' . strtotime(I('get.create_time_beg')) : '';

        $where .= I('get.create_time_end') != '' ? ' and create_time < ' . strtotime(I('get.create_time_end')) : '';

//		$where .= I('get.check_status') !=''? ' and check_status='.I('get.check_status') : ' and check_status'.$check_status;

        $where .= $status == null ? '' : ' and (u.status' . $status;

        $where .= $check_status == null ? '' : ' and check_status' . $check_status;


        $admin	 =session('adminInfo');

        if($admin['gpid']==0){
        }
        else{
            $where =' gpid='.$admin['gpid'];
        }
        if($admin['remark'] == '业务员'){
            $where .=' and admin_id='.$admin['id'];
        }

        $list = $this->getList('u.*,b.bank_short_name', 'user u', $where, 'id desc', true, 'left join app_bank b on u.loan_bank_id=b.id ');

        foreach ($list as $key => $value) {
            $group = $this->getInfo('*', 'group', 'id=' . $value['gpid']);
            $list[$key]['group_name'] = $group['name'];
        }
        return $list;
    }

    /**
     * [担保人信息修改]
     * @return [type] [渲染担保人详细页面]
     * @author [NYJ]
     */
    public function editAssure()
    {
        if (IS_POST) {
            $_tmpData = [];
            $nAssureId = I('post.id');
            $_tmp = $this->getInfo('id,user_id', 'assure', ['id' => $nAssureId]);

            unset($_POST['id']);
            $_POST['home_areaID'] = $this->getAreaIDByPCD($_POST['home_district'], $_POST['home_city'], $_POST['home_province']);
            $_POST['now_areaID'] = $this->getAreaIDByPCD($_POST['now_district'], $_POST['now_city'], $_POST['now_province']);
            $_POST['company_areaID'] = $this->getAreaIDByPCD($_POST['com_district'], $_POST['com_city'], $_POST['com_province']);
            $_POST['update_time'] = time();

            $retUpdate = $this->updateData($_POST, 'assure', 2, ['id' => $nAssureId]);

            if ($retUpdate) {
                $this->success('修改成功', U('Apply/detail_info?user_id=' . $_tmp['user_id']));
            } else {
                $this->error('修改失败', U('Apply/editAssure?assure_id=' . $nAssureId));
            }
        }
        $nAssureId = I('get.assure_id');
        $assureInfo = $this->getInfo('*', 'assure', ['id' => $nAssureId]);
        $com_area = $this->getAreaInfo($assureInfo['company_areaid']);
        $home_area = $this->getAreaInfo($assureInfo['home_areaid']);
        $now_area = $this->getAreaInfo($assureInfo['now_areaid']);

        $this->assign('assure', $assureInfo);
        $this->assign('educationItems', $this->educationItems);
        $this->assign('houseTypeItems', $this->houseTypeItems);
        $this->assign('home_area', $home_area);
        $this->assign('now_area', $now_area);
        $this->assign('com_area', $com_area);
        $this->display();
    }


}